package com.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.DTO.EmployeeAddDAO;
import com.boot.DTO.EmployeeLoginDTO;
import com.boot.Vo.ChangePasswordVo;
import com.boot.Vo.EmployeePageVo;
import com.boot.interceptor.BaseContext;
import com.boot.pojo.Employee;
import com.boot.properties.AccountProperties;
import com.boot.result.Result;
import com.boot.result.ResultCodeNum;
import com.boot.service.EmployeeService;
import com.boot.mapper.EmployeeMapper;
import com.boot.utils.JwtUtil;
import com.boot.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author liyan
 * @description 针对表【employee(员工信息)】的数据库操作Service实现
 * @createDate 2025-04-17 15:50:40
 */
@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee>
        implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Result login(EmployeeLoginDTO employeeLoginDTO) {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<Employee>();
        queryWrapper.eq(Employee::getUsername, employeeLoginDTO.getUsername());
        Employee employee = employeeMapper.selectOne(queryWrapper);
        if (employee != null) {
            String MD5Password = MD5Util.encrypt(employeeLoginDTO.getPassword());
            if (employee.getPassword().equals(MD5Password)) {
                if (Objects.equals(employee.getStatus(), AccountProperties.DISABLE)) {
                    return Result.build(null, ResultCodeNum.ACCOUNT_LOCKED);
                }
                String token = jwtUtil.createToken(employee.getId());
                String refreshToken = jwtUtil.CrateRefreshToken(employee.getId());
                return Result.success(Map.of(
                        "token", token,
                        "refreshToken", refreshToken,
                        "name", employee.getUsername(),
                        "userName", employee.getUsername()
                ));
            }
            return Result.build(null, ResultCodeNum.PASSWORD_ERROR);
        }
        return Result.build(null, ResultCodeNum.USERNAME_ERROR);
    }

    @Override
    public Result save(Employee employee, String token) {
        log.info("新增员工：{}",employee.toString());
        employee.setDefault();
        int insertRow = employeeMapper.insert(employee);
        if (insertRow > 0) {
            return Result.success(employee);
        } else {
            return Result.build(null, ResultCodeNum.INSERT_ERROR);
        }
    }

    @Override
    public Result getEmployeeList(EmployeePageVo employeePageVo) {
        IPage<Employee> page = new Page<>(employeePageVo.getPage(), employeePageVo.getPageSize());
        employeeMapper.selectMyPage(page, employeePageVo);
        List<Employee> list = page.getRecords();
        Map<String, Object> result = new HashMap<>();
        result.put("total", page.getTotal());
        result.put("records", list);
        return Result.success(result);
    }

    @Override
    public Result getEmployeeById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        if (employee != null) {
            return Result.success(employee);
        }
        return Result.build(null, ResultCodeNum.EMPLOYEE_NOT_EXIST);
    }

    @Override
    public Result updateStatus(Integer status, Long userId) {
        LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<Employee>();
        updateWrapper.eq(Employee::getId,userId)
                        .set(Employee::getStatus, status);
        int updateRow = employeeMapper.update(updateWrapper);
        if (updateRow > 0) {
            return Result.success();
        }
        return Result.build(null, ResultCodeNum.UPDATE_ERROR);
    }

    @Override
    public Result updateEmployee(EmployeeAddDAO employeeAddDAO, String token) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeAddDAO,employee);
        employee.setDefault();
        Long OperatorId = jwtUtil.getUserId(token);
        employee.setUpdateUser(OperatorId);
        int updateRow = employeeMapper.updateById(employee);
        if (updateRow > 0) {
            return Result.success();
        }
        return Result.build(null, ResultCodeNum.UPDATE_ERROR);
    }

    @Override
    public Result editPassword(ChangePasswordVo changePasswordVo) {
        Long userId = BaseContext.getCurrentId();
        if (userId == null || userId == 0) {
            return Result.build(null, ResultCodeNum.NOTLOGIN);
        }
        Employee employee = employeeMapper.selectById(userId);
        if (employee == null) {
            return Result.build(null, ResultCodeNum.EMPLOYEE_NOT_EXIST);
        }
        String oldPassword = changePasswordVo.getOldPassword();
        if (!MD5Util.encrypt(oldPassword).equals(employee.getPassword())) {
            return Result.build(null, ResultCodeNum.EMPLOYEE_OLD_PASSWORD_ERROR);
        }
        LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Employee::getId, userId)
                .set(Employee::getPassword, MD5Util.encrypt(changePasswordVo.getNewPassword()));
        int updateRow = employeeMapper.update(updateWrapper);
        if (updateRow == 0) {
            return Result.build(null, ResultCodeNum.EMPLOYEE_CHANGE_PASSWORD_ERROR);
        }
        return Result.success();
    }
}




